import Vue from 'vue';
import Vuex from 'vuex';
import cookies from 'vue-cookies';

Vue.use(Vuex);

const store = new Vuex.Store({
    state: {
        token: cookies.get('token') || '',
        userInfo: {
            account: cookies.get('account') || '',
            nickname: cookies.get('nickname') || '',
            avatar: cookies.get('avatar') || '',
            uniqueId: cookies.get('uniqueId') || '',
            createdAt: cookies.get('createdAt') || '',
        },
    },
    getters: {
        /**
         * token信息
         * @param {*} state 
         * @returns 
         */
        token: state => state.token,
        /**
         * 用户信息
         * @param {*} state 
         * @returns 
         */
        userInfo: state => state.userInfo,
    },
    mutations: {
        // 设置token
        setToken(state, token) {
            state.token = token;
            cookies.set('token', token);
        },
        // 移除token
        removeToken(state) {
            state.token = '';
            cookies.remove('token');
        },
        // 设置用户信息
        setUserInfo(state, userInfo) {
            state.userInfo = userInfo;
            cookies.set('account', userInfo.account);
            cookies.set('nickname', userInfo.nickname);
            cookies.set('avatar', userInfo.avatar);
            cookies.set('uniqueId', userInfo.uniqueId);
            cookies.set('createdAt', userInfo.createdAt);
        },
        // 清除用户信息
        clearUserInfo(state) {
            state.userInfo = {
                account: '',
                nickname: '',
                avatar: '',
                uniqueId: '',
                createdAt: '',
            };
            cookies.remove('account');
            cookies.remove('nickname');
            cookies.remove('avatar');
            cookies.remove('uniqueId');
            cookies.remove('createdAt');
        }
    },
    actions: {
        /**
         * 设置token
         * @param {*} param0 
         * @param {*} token string
         */
        setToken({ commit }, token) {
            commit('setToken', token);
        },
        /**
         * 移除token
         * @param {*} param0 
         */
        removeToken({ commit }) {
            commit('removeToken');
        },
        /**
         * 设置用户信息
         * @param {*} param0 
         * @param {*} userInfo account, nickname, avatar, uniqueId, createdAt
         */
        setUserInfo({ commit }, userInfo) {
            commit('setUserInfo', userInfo);
        },
        /**
         * 清除用户信息
         * @param {*} param0 
         */
        clearUserInfo({ commit }) {
            commit('clearUserInfo');
        }
    }
});

export default store;